<template>
  <section class="f-order-sale">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">商品列表</span>
        <div style="margin-left:auto;">
          <el-button type="primary" @click="lookAdd()">+ 新增商品</el-button>
        </div>
      </div>

      <div class="my-search-box">
        <div>
          <span>商品名称：</span>
          <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称" />
        </div>

        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>
      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe>
          <el-table-column type="index" width="80" label="序号" />
          <el-table-column prop="smallImage" label="缩略图">
            <template v-slot="scope">
              <el-image style="width: 80px; height: 80px" :src="scope.row.smallImage" :zoom-rate="1.2" :max-scale="7"
                :min-scale="0.2" fit="cover" :preview-src-list="[scope.row.smallImage]" preview-teleported />
            </template>
          </el-table-column>
          <el-table-column label="商品信息" width="300">
            <template v-slot="scope">
              <el-link type="primary" style="font-size: 12px" @click="lookDetail(scope.row)">
                {{ scope.row.name }}
              </el-link>
              <p>商品ID：{{scope.row.productId || '--'}}</p>
              <p>商品标题：{{scope.row.title || '--'}}</p>
            </template>
          </el-table-column>
          <el-table-column label="起始价格(元)">
            <template v-slot="scope">
              {{ scope.row.startPrice/100  }}
            </template>
          </el-table-column>
          <el-table-column label="最高价格(元)">
            <template v-slot="scope">
              {{ scope.row.maxPrice/100  }}
            </template>
          </el-table-column>
          <el-table-column label="限制年限">
            <template v-slot="scope">
              {{ scope.row.limitYears  }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="商品状态">
            <template v-slot="scope">
              <p :style="{'color': statusColor[scope.row.status]}">{{ scope.row.status == 1? '上架': '下架' }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
            <template v-slot="scope">
              {{ getDateTime(scope.row.createTime)[6] || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="Operations" label="操作" align="center">
            <template v-slot="scope">
              <el-link v-if="scope.row.status == 1" style="font-size:12px" type="warning"
                @click="settingHandle(scope.row,'下架',0)">下架</el-link>
              <el-link v-if="scope.row.status == 0" style="font-size:12px" type="success"
                @click="settingHandle(scope.row,'上架',1)">上架</el-link>
              <el-link v-if="scope.row.status == 0" class="f-ml-20" style="font-size:12px" type="danger"
                @click="settingHandle(scope.row,'删除','delete')">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>

    </div>

    <!-- 确认密码 -->
    <confirm-password ref="confirmPasswordRef" @verification="confirmSuccess" />

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad, setStore } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import confirmPassword from '@/components/confirmPass.vue'
import api from './api'

export default {
  components: { confirmPassword },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const confirmPasswordRef = ref(null)

    const state = reactive({
      isDetail: false,

      searchForm: {
        "createTimeEnd": '',
        "createTimeStart": '',
        "limitYears": '',
        "maxStartPrice": '',
        "minStartPrice": '',
        "name": "",
        "status": '',
        "title": ""
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      currentType: '',
      currentData: {},

      statusColor: {
        '0': '#E6A23C',
        '1': '#67C23A',
      }
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/goodsManage')
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.tableData = []
      state.searchForm = {
        "createTimeEnd": '',
        "createTimeStart": '',
        "limitYears": '',
        "maxStartPrice": '',
        "minStartPrice": '',
        "name": "",
        "status": '',
        "title": ""
      }
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        "orderBy": "id desc",
      }

      api.goodsList(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.records
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function lookDetail(data) {
      router.push({
        path: '/goodsManage/detail',
        query: {
          productId: data.productId,
        }
      })
      setStore('grantInfo', data)
    }

    function lookAdd() {
      router.push({ path: '/goodsManage/add' })
    }

    function settingHandle(params, title1, type) {
      state.currentData = params
      state.currentType = type
      const title = `商品${title1}提示`
      const msg = `您确定要将所选的商品${title1}吗？`
      confirmPasswordRef.value.dialogShow(title, msg)
    }

    function confirmSuccess() {
      if (state.currentType == 'delete') {
        api.goodsDelete({ productId: state.currentData.productId }).then(res => {
          successDeal('删除成功')
          getTableData()
        }).catch(err => {
          console.log(err)
        })
      } else {
        api.goodsStatus({ productId: state.currentData.productId, status: state.currentType }).then(res => {
          successDeal('操作成功')
          getTableData()
        }).catch(err => {
          console.log(err)
        })
      }
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 290
      setIsDetail()
    })

    return {
      ...toRefs(state),
      confirmPasswordRef,
      searchHandle,
      resetHandle,
      lookDetail,
      lookAdd,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      settingHandle,
      confirmSuccess,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-order-sale {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;

      > .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 400px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 120px;
          text-align: right;
        }
      }

      .datebox {
        width: 400px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: space-around;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
}
</style>